package com.example.aerohub.exception;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.example.aerohub.pojo.resp.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Date;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 请求方式不支持
	 */
	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public Resp handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
		return Resp.error(ErrorCode.NO_METHOD_SUPPORTED);
	}

	/**
	 * 业务异常
	 */
	@ExceptionHandler(GeneralException.class)
	public Resp handleServiceException(GeneralException e) {
		log.error(e.getMessage(), e);
		return Resp.error(e.getCode(),e.getMessage());
	}

	/**
	 * 请求路径中缺少必需的路径变量
	 */
	@ExceptionHandler(MissingPathVariableException.class)
	public Resp handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求路径中缺少必需的路径变量'{}',发生系统异常.", requestURI, e);
		return Resp.error(String.format("请求路径中缺少必需的路径变量[%s]", e.getVariableName()));
	}

	/**
	 * 请求参数类型不匹配
	 */
	@ExceptionHandler(MethodArgumentTypeMismatchException.class)
	public Resp handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		String value = Convert.toStr(e.getValue());
		if (StrUtil.isNotEmpty(value)) {
			value = com.ysf.inf.utils.EscapeUtil.clean(value);
		}
		log.error("请求参数类型不匹配'{}',发生系统异常.", requestURI, e);
		return Resp.error(String.format("请求参数类型不匹配，参数[%s]要求类型为：'%s'，但输入值为：'%s'", e.getName(), e.getRequiredType().getName(), value));
	}

	/**
	 * 拦截未知的运行时异常
	 */
	@ExceptionHandler(RuntimeException.class)
	public Resp handleRuntimeException(RuntimeException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',发生未知异常.", requestURI, e);
		return Resp.error(e.getMessage());
	}

	/**
	 * 拦截的校验异常
	 */
	@ExceptionHandler(ConstraintViolationException.class)
	public Resp handleConstraintViolationException(ConstraintViolationException e) {
		String msg = e.getMessage();
		if (CollUtil.isNotEmpty(e.getConstraintViolations())) {
			ConstraintViolation<?> violation = CollUtil.getFirst(e.getConstraintViolations());
			if (violation != null) {
				String validMsg = violation.getMessage();
				if (StrUtil.isNotEmpty(validMsg)) {
					msg = validMsg;
				}
			}
		}
		return Resp.error(msg);
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception.class)
	public Resp handleException(Exception e, HttpServletRequest request) {
		try{
			Date start = (Date) request.getAttribute("_time");
			long expired = DateUtil.between(start, new Date(), DateUnit.MS);
			String requestURI = request.getRequestURI();
			log.error("请求地址'{}, expired: {}ms',发生系统异常.", requestURI, expired, e);
		}catch (Exception exception){

		}
		return Resp.error(e.getMessage());
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(BindException.class)
	public Resp handleBindException(BindException e) {
		log.error(e.getMessage(), e);
		String message = e.getAllErrors().get(0).getDefaultMessage();
		return Resp.error(message);
	}

	/**
	 * 自定义验证异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		log.error(e.getMessage(), e);
		String message = e.getBindingResult().getFieldError().getDefaultMessage();
		return Resp.error(message);
	}

}